from django.db import models
from django.conf import settings
from apps.system.models import Category
from django.utils import timezone, html


# Create your models here.


class Article(models.Model):
    DRAFT = 0
    RELEASE = 1
    PUBLIC = 2

    STATUS_CHOICE = (
        (DRAFT, '草稿'),
        (RELEASE, '发布'),
        (PUBLIC, '公开')
    )

    title = models.CharField(verbose_name='标题', max_length=100)
    content = models.TextField(verbose_name='内容', null=True)
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICE, default=DRAFT)
    excerpt = models.CharField(verbose_name='摘要', max_length=200, null=True)
    category = models.ForeignKey(Category, verbose_name='标签', on_delete=models.CASCADE, related_name='article_category')
    tags = models.ManyToManyField(Category, verbose_name='标签', related_name='article_tags')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='作者', on_delete=models.CASCADE)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    modified_time = models.DateTimeField(verbose_name='修改时间', null=True)
    delete = models.BooleanField(verbose_name='删除', default=False)

    class Meta:
        db_table = 'article'
        verbose_name = '文章'
        ordering = ['-create_time',]

    # 覆写模型的 save 方法，在数据被保存到数据库前
    def save(self, *args, **kwargs):
        self.modified_time = timezone.now()
        if self.content:
            self.excerpt = html.strip_tags(self.content[:54])
        super().save(*args, **kwargs)
